// request请求封装，支持Promise

let request = {
	// BaseURL
	baseURL: "http://www.shop.net/api",
	ajax({ url, data, method, header, ...config }) {
		// 拼接完整的API接口地址
		url = this.baseURL + url;
		// 提取token
		let token = uni.getStorageSync('token');
		// 默认headers设置
		let default_header = {
			"Authori-zation": `Bearer ${token}`,
			"Content-Type": 'application/json',
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				data,
				method,
				// 将两个header进行合并，后面的优先级更大，如果传了header则会覆盖默认header
				header: { ...default_header, ...header },
				...config,
				// 使用success接收返回的数据
				success(res) {
					let { statusCode, header, errMsg, data, cookies } = res;
					// 根据状态码statusCode判断
					switch (statusCode) {
						case 200:
							resolve(data);
							break;
						case 404:
							uni.showToast({
								title: `错误码：${statusCode}，登录认证失败！`,
								icon: "none",
							});
							reject(res);
							break;
						case 401:
							uni.showToast({
								title: `错误码：${statusCode}，API接口地址错误！`,
								icon: "none",
							});
							reject(res);
							break;
						case 500:
							uni.showToast({
								title: `错误码：${statusCode}，请联系后端程序！`,
								icon: "none",
							});
							reject(res);
							break;
						default:
							uni.showToast({
								title: `错误码：${statusCode}，服务器错误！`,
								icon: "none",
							});
							reject(res);
							break;
					}
				},
			});
		});
	},

	get(url, data, header, ...config) {
		try {
			// return的是Promise对象
			return this.ajax({ url, data, method: "GET", header, ...config });
		} catch (error) {
			console.log(error);
		}
	},
	post(url, data, header, ...config) {
		try {
			// return的是Promise对象
			return this.ajax({ url, data, method: "POST", header, ...config });
		} catch (error) {
			console.log(error);
		}
	},
	put(url, data, header, ...config) {
		try {
			// return的是Promise对象
			return this.ajax({ url, data, method: "PUT", header, ...config });
		} catch (error) {
			console.log(error);
		}
	},
	delete(url, data, header, ...config) {
		try {
			// return的是Promise对象
			return this.ajax({ url, data, method: "DELETE", header, ...config });
		} catch (error) {
			console.log(error);
		}
	},
}

export default request;